package com.course.redisson.service;

import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RQueue;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @PROJECT_NAME: course
 * @DESCRIPTION: 队列消费者
 * @Author: 涂玄武
 * @DATE: 2021/6/3 10:35
 */
@Component
public class QueueConsumer implements ApplicationRunner, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(QueueConsumer.class);

    @Resource
    private RedissonClient redissonClient;

    /**
     * 创建线程池去消费消息
     */
    public static ExecutorService queueThreadPool = Executors.newFixedThreadPool(1);

    @Override
    public void run(ApplicationArguments args) throws Exception {
        queueThreadPool.execute(() -> {
            //定义基本队列的名称
            final String queueName = "redissonBasicQueue";
            //获取队列的实例
            RQueue<String> rQueue = redissonClient.getQueue(queueName);
            while (true) {
                //从队列中弹出消息
                String msg = rQueue.poll();
                if (StringUtils.isNotBlank(msg)) {
                    logger.info("队列的消费者-监听消费消息：{}", msg);

                    //TODO:在这里执行相应的业务逻辑
                }
            }
        });
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
